using Avalonia.BiliBili.Libs.Window;
using Avalonia.BiliBili.Views.ChildViews.Search;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Bilibili.Common.Log;
using Bilibili.Model.Common;
using Bilibili.WebClient.Api;
using PCLUntils.IEnumerables;
using PCLUntils.Objects;
using System;

namespace Avalonia.BiliBili.Views
{
    public partial class SearchView : View
    {
        public SearchClient Client { get; }
        public SearchView()
        {
            InitializeComponent();
            Client = new SearchClient();
        }
        public override void AfterInitializeComponent()
        {
            typeTab.SelectionChanged += TypeTab_SelectionChanged;
            btnSearch.Click += BtnSearch_Click;
        }
        private void TypeTab_SelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.FindItem(0) is TabItem tabItem && keywords.Text.IsNotEmpty())
                {
                    var text = Uri.EscapeDataString(keywords.Text);
                    var data = new InvokeData<string>(true, text);
                    var childView = tabItem.Content as ChildView;
                    childView.Base = this;
                    childView?.Callback(data);
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("TypeTabSelectionChanged", ex);
            }
        }
        private void BtnSearch_Click(object? sender, RoutedEventArgs e)
        {
            RunOnUiThread(() =>
            {
                if (keywords.Text.IsNotEmpty())
                {
                    var type = typeTab.SelectedIndex;
                    var text = Uri.EscapeDataString(keywords.Text);
                    var data = new InvokeData<string>(true, text);
                    var tabItem = typeTab.Items.GetItem<TabItem>(type);
                    var childView = tabItem.Content as ChildView;
                    childView.Base = this;
                    childView?.Callback(data);
                }
            });
        }
        public void ShowLive() => typeTab.SelectedIndex = 2;
    }
}